package com.web_bloks.project.controllers.client;

import com.google.gwt.core.client.GWT;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

import com.web_bloks.system.client.Logger;

import com.web_bloks.document.client.Document;
import com.web_bloks.document.client.DocumentManager;
import com.web_bloks.document.client.DocumentAnalyzer;
import com.web_bloks.document.client.DocumentListener;
import com.web_bloks.document.client.Title;
import com.web_bloks.document.client.TitleException;
import com.web_bloks.document.client.Namespace;
import com.web_bloks.document.client.NamespaceException;

import com.web_bloks.user.client.User;
import com.web_bloks.user.client.UserManager;

import com.web_bloks.widget.client.StatusWidget;
import com.web_bloks.types.client.StateType;
/**
 * ToolsController
 * 
 * @author Jean-Lou Dupont
 *
 */
public class ToolsController 
	implements DocumentListener {

	StatusWidget statusIcon = null;
	
	Button editButton = null;
	Button saveButton = null;
	Button loadButton = null;
	Button clearCacheButton = null;
	Label titleLabel = null;
	TextBox titleTextBox = null;

	Document doc = null;
	DocumentManager dm = null;
	
	User currentUser = null;
	
	boolean userIsAdmin = false;

	PostController pc = null;
	
	/*===================================================================
	 * CONSTRUCTORS
	 ===================================================================*/

	public ToolsController() {
		
	}
	
	/*===================================================================
	 * CONFIGURATION
	 ===================================================================*/
	public void setPostController(PostController pc) {
		this.pc = pc;
	}
	public void setStatusIcon(StatusWidget status) {
		statusIcon = status;
	}
	public void setEditButton(Button edit) {
		editButton = edit;
	}
	public void setSaveButton(Button save) {
		saveButton = save;
	}
	public void setLoadButton(Button load) {
		loadButton = load;
	}
	public void setClearCacheButton(Button cc) {
		clearCacheButton = cc;
	}
	public void setTextBoxTitle(TextBox ttb) {
		titleTextBox = ttb;
	}
	public void setLabelTitle(Label lt) {
		titleLabel = lt;
	}
	public void setDocumentManager(DocumentManager dm) {
		this.dm = dm;
	}
	/*===================================================================
	 * Edit Button
	 ===================================================================*/
	public void onEditButtonClick() {
		logInfo("onEditButtonClick");
		
		//try loading the page in the 'raw' namespace
		Namespace rawns = null;
		Title rawtitle = null;
		
		if ( null == doc ) {
			return;
		}
		Title title = doc.getPageTitle();
		
		try {
			rawns = Namespace.createRaw(title.getNamespace());
			rawtitle = Title.newFromParts(rawns, title.getName());			
		} catch(NamespaceException e) {
			Logger.logWarn(this.getClass()+".onEditButtonClick: NamespaceException raised");
		}

		if ( null == rawtitle )
			return;
		
		dm.load(rawtitle.toString());
		
	}///
	
	
	/*===================================================================
	 * Save Button
	 ===================================================================*/
	public void onSaveButtonClick() {
		logInfo("onSaveButtonClick");

		pc.execute();
		
	}//
	/*===================================================================
	 * Clear Cache Button
	 ===================================================================*/
	public void onClearCacheButtonClick() {
		logInfo("onClearCacheButtonClick");
		dm.clear();
	}
	/*===================================================================
	 * Load Button
	 ===================================================================*/
	public void onLoadButtonClick() {
		logInfo("onLoadButtonClick");
		
		Title title, rawTitle;
		Namespace ns, nsRaw;
		String name, titleName = null;
		
		// Retrieve title
		String reqName = titleTextBox.getText();
		
		// Verify requested title validity
		try {
			//requested title
			title = Title.newFromText(reqName);
			ns    = title.getNamespace();
			name  = title.getName();
			
			//corresponding title in the 'raw' namespace
			nsRaw     = Namespace.createRaw(ns);
			rawTitle  = Title.newFromParts(nsRaw, name);
			titleName = rawTitle.toString();
			
		} catch(TitleException te) {
			title = null;
			Logger.logError(this.getClass()+".onLoadButtonClick: TitleException, msg=" + te.getMessage());
		} catch(NamespaceException ne) {
			title = null;
			Logger.logError(this.getClass()+".onLoadButtonClick: NamespaceException, msg=" + ne.getMessage());
		} catch(Exception e) {
			title = null;
			Logger.logError(this.getClass()+".onLoadButtonClick: Exception, msg=" + e.getMessage());
		}
		
		if ( null == title )
			return;
		
		// Use DocumentManager to load document
		//  from the 'raw' namespace
		dm.load(titleName);
	}

	/*===================================================================
	 * Title textbox
	 ===================================================================*/
	public void onTitleChanged(String title_name) {
		Logger.logInfo(this.getClass()+"onTitleChanged");
	}
	
	/*===================================================================
	 * Content document Events
	 ===================================================================*/
	/**
	 * Sets the state to 'pending'
	 */
	public void onDocumentChanging(String name, String targetRegionName) {
		Logger.logInfo(this.getClass()+".onDocumentChanging");
		
		statusIcon.setStatus(StateType.PENDING);
		editButton.setEnabled(false);
		saveButton.setEnabled(false);
		loadButton.setEnabled(false);
		titleTextBox.setReadOnly(true);
	}
	
	public boolean onDocumentChanged(Document doc) {
				
		boolean doc_valid = false;
		boolean editable = false;
		boolean doc_editable = false;
		
		UserManager um = GWT.create(UserManager.class);
		
		currentUser = um.getCurrentUser();
		userIsAdmin = currentUser.isMemberOf("admin");
		
		if (null != doc)
			doc_valid = doc.getState() == Document.STATE_VALID;
		
		// Set StatusIcon
		// ==============
		if (doc_valid) {
			this.doc = doc;
			doc_editable = DocumentAnalyzer.isEditable(doc) ;
			editable = doc_editable && userIsAdmin;			
		} else {
			doc_editable = false;
			editable = false;			
		}
		
		setButtons( userIsAdmin, doc_valid, doc_editable, editable);

		return false;
		
	}//onDocumentChanged
	
	public void onDocumentRendered(Document doc) {		
	}
	/*===================================================================
	 * 
	 ===================================================================*/
	protected void setButtons(boolean userCanEdit, boolean docValid, boolean docEditable, boolean docSaveable) {
		
		if (docValid) {
			statusIcon.setStatus(StateType.OK);
		} else {
			statusIcon.setStatus(StateType.ERROR);
		}

		clearCacheButton.setVisible(userCanEdit);
		clearCacheButton.setEnabled(userCanEdit);
		
		editButton.setEnabled(userCanEdit);
		editButton.setVisible(userCanEdit);
		
		loadButton.setEnabled(userCanEdit);		
		loadButton.setVisible(userCanEdit);
			
		saveButton.setEnabled(docSaveable);
		saveButton.setVisible(userCanEdit);
		
		// Title label & textbox
		titleTextBox.setReadOnly(!userCanEdit);		
		titleTextBox.setVisible(userCanEdit);

		titleLabel.setVisible(userCanEdit);
		
	}
	
	/*===================================================================
	 * HELPERS
	 ===================================================================*/
	private void logInfo(String msg) {
		Logger.logInfo(this.getClass()+"."+msg);
	}
}//END